package com.ifast.common.service.impl;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ifast.common.base.CoreServiceImpl;
import com.ifast.common.dao.UpdateDao;
import com.ifast.common.domain.Update;
import com.ifast.common.service.UpdateService;
import com.ifast.common.utils.Const;
import com.ifast.common.utils.GenUtils;
import com.ifast.common.utils.alioss.UploadResult;
import com.ifast.common.utils.alioss.UploadUtils;
import com.luculent.util.extension.api.Result;

import cn.hutool.core.collection.CollectionUtil;

/**
 * @ClassName UpdateServiceImpl
 * @Author ShiQiang
 * @Date 2019年4月24日10:38:43
 * @Version v1.0
 */
@Service
public class UpdateServiceImpl extends CoreServiceImpl<UpdateDao, Update> implements UpdateService {
    
	@Override
    public Update getUpdate(String type){ 
		return this.selectOne(new EntityWrapper<Update>().eq("type", type));  
    }
	
	@Override
	public Result<?> add(HttpServletRequest request,Update update) throws IOException{ 
		
		if(StringUtils.isBlank(update.getType()))
			return Result.fail_msg("缺少必要参数"); 
		
		//上传文件
		Configuration conf = GenUtils.getConfig();
		UploadResult result = UploadUtils.uploadLocation(request,"file",conf.getString("file"),Const.maxApkSize);
		if(CollectionUtil.isNotEmpty(result.getFileURLs())){
			update.setUpdateUrl(result.getFileURLs().get(0)); 
			update.setMd5(DigestUtils.md5DigestAsHex(new FileInputStream(result.getUrlAndSize().get(0).get(result.getFileURLs().get(0)).toString())));
		}  
		Update oldUpdate = this.selectOne(new EntityWrapper<Update>().eq("type", update.getType())); 
		if(oldUpdate == null){ 
			return this.insert(update)?Result.ok():Result.fail();
		}else{
			oldUpdate.setForced(update.isForced())
			.setIgnore(update.isIgnore())
			.setUpdateContent(update.getUpdateContent())
			.setVersionCode(update.getVersionCode())
			.setVersionName(update.getVersionName()); 
			if(StringUtils.isNotBlank(update.getUpdateUrl())){
				oldUpdate.setUpdateUrl(update.getUpdateUrl());
				oldUpdate.setMd5(update.getMd5());
			}
			return this.updateById(oldUpdate)?Result.ok():Result.fail();
		}  
	} 
}
